// 将数据读取到内存中，在
const { writeFile, readFileSync, existsSync } = require('fs');
const { join } = require('path');
const filename = join(__dirname, './minidb.db');
let cache = {};
if (existsSync(filename)) {
  cache = JSON.parse(readFileSync(filename));
}

let timer = null;
const updateDb = () => {
  clearTimeout(timer);
  timer = setTimeout(() => {
    writeFile(filename, JSON.stringify(cache), (error) => {
      if (error) {
        console.log('存储异常', error)
      }
    });
  }, 500);
};

module.exports = {
  get: (key = null, def = null) => {
    return key in cache ? cache[key] : def;
  },
  set: (key, value) => {
    cache[key] = value;
    updateDb();
    return true;
  },
  del: (key = null) => {
    delete cache[key];
    updateDb();
    return true;
  },
};